﻿using System;

using Mojo;
using Mojo.Menus;
using Mojo.Widgets;

namespace McDonalds
{
    [NoCompile]
    public class CouponListModel
    {
        public Coupon[] items;
    }

    [NoCompile]
    public class Attachment
    {
        public string fullPath;
        public string mimeType;
    }

    [NoCompile]
    public class DownloadManagerOnSuccessResult
    {
        public bool returnValue;
        public int ticket;
        public bool completed;
        public string destFile;
    }

    [ImportClass(String.Empty, "MainAssistant")]
    public class MainAssistant : AbstractSceneAssistant
    {
        public MainAssistant()
        {
        }

        private Scrim scrim;
        private bool toggleFullorBuyOnly;
        private ListModel couponListModel;
        private int downloadImageProgress;

        private MenuCreateModel viewMenuModel;
        private WidgetsCreateAttributes viewMenuAttributes;
        public override void Setup()
        {
            //Note: it's not initialized, so add this statement here.
            this.couponListModel = new object() as ListModel;

            // this function is for setup tasks that have to happen when the scene is first created
            // use Mojo.View.render to render view templates and add them to the scene, if needed             
            var AddSubMenuAttr = new AppMenuAttributes() { OmitDefaultItems = true };
            var AddSubMenuModel = new MenuCreateModel()
            {
                Visible = true,
                Items = new MenuItem[]{
				            Mojo.Menu.EditItem,
				            Mojo.Menu.HelpItem
                }
            };
            this.controller.SetupWidget(Mojo.Menu.AppMenu, AddSubMenuAttr, AddSubMenuModel);

            // setup widgets here
            this.viewMenuModel = new MenuCreateModel()
            {
                Visible = true,
                Items = new MenuItem[]{
                    new MenuItem()
                    {
                        Items = new object[]{
					            new { label= AppSettings.GetLastUpdateTime() + "(共" + (MCModels.couponList.Length) + "个)", width= 260 },
					            new { command= "do-refresh", icon= "refresh" }
			            }
                    }
                }
            };

            this.viewMenuAttributes = new ViewMenuAttributes()
            {
                SpacerHeight = 50,
                MenuClass = "no-fade"
            };

            this.controller.SetupWidget(Mojo.Menu.ViewMenu, this.viewMenuAttributes, this.viewMenuModel);


            var bottomMenuModel = new MenuCreateModel()
            {
                Visible = true,
                Items = new MenuItem[]{
                      new MenuItem() { IconPath= "smallicon.png", Command= "do-buy"},
                      new MenuItem() {},
                      new MenuItem() { Command= "do-shareViaEmail", Icon= "send" }
                }
            };
            this.controller.SetupWidget(Mojo.Menu.CommandMenu, null, bottomMenuModel);

            this.controller.SetupWidget("ajaxSpinner", new SpinnerAttributes() { SpinnerSize = Mojo.Widget.SpinnerLarge },
                new SpinnerModel() { Spinning = true }
            );


            this.toggleFullorBuyOnly = true;

            this.scrim = Mojo.View.CreateScrim(this.controller.document, new
            {
                scrimClass = "palm-scrim"
            });
            this.controller.Get("ajaxLoading").AppendChild(this.scrim).AppendChild(Mojo.Global._("ajaxSpinner"));
            this.scrim.Hide();

            var couponListAttr = new ListAttributes()
            {
                ItemTemplate = "main/couponItem-Template",
                SwipeToDelete = false,
                RenderLimit = 40,
                Reorderable = false
            };

            this.couponListModel = new ListModel()
            {
                Items = new object[0]
            };            

            this.controller.SetupWidget("couponListWgt",
                couponListAttr,
                this.couponListModel
            );

            var checkboxCouponAttribs = new CheckBoxAttributes()
            {
                ModelProperty = "ck",
                DisabledProperty = "dis"
            };

            this.controller.SetupWidget("checkboxCoupon", checkboxCouponAttribs, new CheckBoxModel() { });

            // add event handlers to listen to events from widgets                     
            this.LoadCoupon();
        }

        public override void Deactivate(Event events)
        {
        }

        public override void Cleanup(Event events)
        {
            AppSettings.SaveCoupon();
        }


        public override void HandleCommand(Event events)
        {
            //Extend:this seems a bug in compiler API, in release notes said switch statement is not fully supported.
            //if move this declare into a 'case' block, it iwll cause a error, need further investigate.
            var attachmentsList = new Attachment[0];

            if (events.type == Mojo.Event.command)
            {
                switch (events.Command)
                {
                    case "do-refresh":
                        this.RefreshCoupon();
                        break;

                    case "do-buy":
                        this.toggleFullorBuyOnly = !this.toggleFullorBuyOnly;

                        if (this.toggleFullorBuyOnly == true)
                        {
                            this.couponListModel.Items = MCModels.GetCouponList();
                            this.controller.ModelChanged(this.couponListModel);
                        }
                        else
                        {
                            this.couponListModel.Items = MCModels.GetBuyList();
                            this.controller.ModelChanged(this.couponListModel);
                        }

                        break;

                    case "do-shareViaEmail":

                        for (var i = 0; i < this.couponListModel.Items.Length; i++)
                        {
                            var coupon = this.couponListModel.Items[i] as Coupon;
                            Attachment attachment = new Attachment() { fullPath = coupon.lIU, mimeType = "image/jpg" };
                            attachmentsList.Push(attachment);
                        }

                        this.controller.ServiceRequest(PalmServices.ApplicationManager, new Mojo.Service.Request()
                        {
                            method = "launch",
                            parameters = new
                            {
                                id = "com.palm.app.email",


                                @params = new
                                {
                                    summary = "最新的麦当劳优惠券",
                                    text = "看在好友的份上才发给你的哦，不用谢我了。",
                                    attachments = attachmentsList
                                }

                            }
                        });

                        break;
                }
            }
        }

        private void RefreshCoupon()
        {
            this.scrim.Show();

            var r = new Ajax.Request(AppSettings.CouponRequestURI, new Ajax.AjaxRequestOptions()
            {
                method = "GET",
                encoding = "UTF-8",
                bodyencoding = "UTF-8",
                evalJSON = false,
                onSuccess = new Action<Ajax.Transport>(RefreshCouponSuccess).Bind(this),
                onFailure = new Action<Ajax.Transport>(RefreshCouponFailure).Bind(this),
            });
        }

        private void RefreshCouponSuccess(Ajax.Transport transport)
        {
            this.scrim.Hide();

            try
            {
                var htmlstring = transport.responseText;
                var couponstring = htmlstring.Match(AppSettings.RegExp);

                MCModels.couponList = new Coupon[0];

                for (var i = 0; i < couponstring.Length; i++)
                {

                    var startPos = couponstring[i].IndexOf("\"") + 1;
                    var stopPos = couponstring[i].LastIndexOf("\"");
                    if (startPos >= 0 && stopPos >= 0)
                    {
                        string tempImageUrl = couponstring[i].Substring(startPos, stopPos);
                        tempImageUrl = AppSettings.CouponDirectoryURI + tempImageUrl;
                        //tempImageUrl = tempImageUrl.Replace("mclub/../", "");
                        var coupon = new { iU = tempImageUrl, lIU = "", ck = false, dis = false };
                        MCModels.couponList.Push(coupon);
                    }
                }

                //update the display
                this.couponListModel.Items = MCModels.couponList;
                this.controller.ModelChanged(this.couponListModel);

                //update the last updated time
                AppSettings.SetLastUpdateTime(new DateTime());
                this.UpdateViewMenu();
                //download image to local cache
                this.DownloadImages();
            }
            catch (Exception e)
            {
                Mojo.Log.Error(e.ToString());
            }
        }

        private void RefreshCouponFailure(object transport)
        {
            this.scrim.Hide();
            Mojo.Log.Error("refreshCouponFailure");
        }

        private void UpdateViewMenu()
        {
            this.viewMenuModel["items"] = new object[]{
                new {
                    items = new object[]{
                        new {label= AppSettings.GetLastUpdateTime() + "(共" + (MCModels.couponList.Length) + "个)", width= 260},
                        new { command= "do-refresh", icon= "refresh" }
                    }
                }
            };
            this.controller.ModelChanged(this.viewMenuModel);
        }

        private void LoadCoupon()
        {
            AppSettings.LoadCoupon();
            if (MCModels.couponList != null)
            {
                //display coupon list                
                this.couponListModel.Items = MCModels.couponList;
                this.controller.ModelChanged(this.couponListModel);

                this.UpdateViewMenu();
            }
            else
            {
                this.RefreshCoupon();
            }
        }

        private void DownloadImages()
        {
            try
            {
                this.downloadImageProgress = 0;

                //start display progress
                this.viewMenuModel["items"] = new object[]{
                    new {
                        items = new object[]{
                            new {label= "正在下载第1个，共" + MCModels.couponList.Length + "个", width= 320}  //,
                            //new { command= "do-refresh", icon= "refresh" }
                        }
                    }
                };
                this.controller.ModelChanged(this.viewMenuModel);

                for (var i = 0; i < MCModels.couponList.Length; i++)
                {
                    //Extend:if we put this "inline" will cause an error at compiler -- overload resolution fail, need investigate further
                    var r = new Mojo.Service.Request()
                    {
                        method = "download",
                        parameters = new
                        {
                            target = MCModels.couponList[i].iU,
                            targetDir = "/media/internal/.mcdonaldscoupon/",
                            targetFilename = i + ".jpg",
                            keepFilenameOnRedirect = false,
                            subscribe = true
                        },

                        onSuccess = new Action<Mojo.Service.Response>(DownloadImageSuccess).Bind(this),
                        onFailure = delegate(Mojo.Service.Response resp) { Mojo.Log.Error(resp); }
                    };

                    this.controller.ServiceRequest(PalmServices.DownloadManager, r);
                }
            }
            catch (Exception e)
            {
                Mojo.Log.Error(e.ToString());
            }
        }

        private void DownloadImageSuccess(Mojo.Service.Response transport)
        {
            object temp = transport;
            DownloadManagerOnSuccessResult result = temp as DownloadManagerOnSuccessResult;
            if (result.completed == true)
            {
                string fileName = result.destFile;
                int i = System.Global.ParseInt(fileName.Replace(".jpg", ""));
                MCModels.couponList[i].lIU = "/media/internal/.mcdonaldscoupon/" + i + ".jpg";
                //MCModels.couponList[i].iU = MCModels.couponList[i].lIU;
                //TODO
                MCModels.couponList[i].iU = "";
                this.PostDownloadProgressMessage(i);
            }
        }

        private void PostDownloadProgressMessage(int i)
        {
            this.downloadImageProgress = this.downloadImageProgress + 1;
            //string msg = "Downloading coupon " + this.downloadImageProgress.ToString() + " of " + MCModels.couponList.Length.ToString();
            //System.Html.Console.Log(msg);
            //Mojo.Controller.GetAppController().ShowBanner(new { messageText = msg }, string.Empty, "notification");
            if (this.downloadImageProgress < MCModels.couponList.Length)
            {
                this.viewMenuModel["items"] = new object[]{
                    new {
                        items = new object[]{
                            new {label= "正在下载第" + (this.downloadImageProgress+1) + "个，共" + MCModels.couponList.Length + "个", width= 320}  //,
                            //new { command= "do-refresh", icon= "refresh" }
                        }
                    }
                };
                this.controller.ModelChanged(this.viewMenuModel);

                //refresh the display
                this.controller.ModelChanged(this.couponListModel);
            }
            else
            {
                //this.UpdateViewMenu();
                AppSettings.SaveCoupon();
                this.LoadCoupon();
            }

        }

    }
}
